﻿using System.Collections.Generic;
using System.Linq;
using cludg.Repository.NHibernate.Sessions;
using NHibernate;
using NHibernate.Linq;

namespace cludg.Repository.Content.NHibernate
{
	using Domain.Content;

	public class TagRepository : ITagRepository
	{
		protected readonly INHibernateSessionController SessionController;

		public TagRepository(INHibernateSessionController sessionController)
		{
			SessionController = sessionController;
		}

		public IQueryable<Tag> Get()
		{
			return SessionController.Current.Linq<Tag>(SessionController.Current.CreateCriteria<Tag>().SetCacheable(true));
		}

		public IEnumerable<TagCount> GetTagContentCounts()
		{
			var q = SessionController.Current.CreateQuery(@"
SELECT
	Name as TagName, COUNT(*) as Count
FROM
	Tag
GROUP BY
	Name");
			return (from object[] entryArray in q.List()
			        select new TagCount {TagName = (string) entryArray[0], Count = (long) entryArray[1]}).ToList();
		}
	}
}
